import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_pickers/pickers.dart';
import 'package:flutter_pickers/time_picker/model/date_mode.dart';
import 'package:flutter_pickers/time_picker/model/pduration.dart';
import 'package:get/get.dart';
import 'package:ty_smart_watch/ble/ble_util.dart';
import 'package:ty_smart_watch/ble/protocol_data_util.dart';
import 'package:ty_smart_watch/page/watch_setting_page/controller/watch_setting_controller.dart';
import 'package:ty_smart_watch/utils/Log.dart';

class WatchPeriodPage extends StatefulWidget {
  const WatchPeriodPage({super.key});

  @override
  State<WatchPeriodPage> createState() => _WatchPeriodPageState();
}

class _WatchPeriodPageState extends State<WatchPeriodPage> {
  int _functionId = 0; //功能id
  String _mac = ""; //设备地址

  final _trailingStyle = const TextStyle(color: Color(0xFF3075E9));
  final _titleStyle = const TextStyle(fontSize: 18);
  final _confirmColor = const Color(0xFF3075E9);
  final _unConfirmColor = const Color(0xFF80A3DF);

  final _controller = Get.put(WatchSettingController());

  @override
  void initState() {
    super.initState();
    _functionId = Get.arguments["id"];
    _mac = Get.arguments["mac"];
    Log.d("页面收到的数据：$_functionId > $_mac");
    _controller.getBleData(_mac, _functionId);
  }

  @override
  Widget build(BuildContext context) {
    ever(
      _controller.needClosePage,
      (need) => {
        Log.d("need close page: $need"),
        if (need == 2) {Get.back()}
      },
    );
    return Scaffold(
      appBar: AppBar(
        title: const Text("生理期提醒"),
        centerTitle: true,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios),
          onPressed: () {
            Get.back();
          },
        ),
      ),
      body: Column(
        children: [
          //开关
          Obx(
            () => SwitchListTile(
              dense: true,
              inactiveThumbColor: _unConfirmColor,
              inactiveTrackColor: _unConfirmColor.withAlpha(88),
              activeColor: _confirmColor,
              activeTrackColor: _confirmColor.withAlpha(88),
              title: Text("开关", style: _titleStyle),
              onChanged: (bool value) {
                var temp = _controller.periodBean.value;
                temp.isSwitch = value;
                _controller.updatePeriodBean(temp);
              },
              value: _controller.periodBean.value.isSwitch,
            ),
          ),

          Obx(
            () => Visibility(
              visible: _controller.periodBean.value.isSwitch,
              child: Column(
                children: [
                  //开始时间
                  ListTile(
                    title: Text("开始时间", style: _titleStyle),
                    trailing: Obx(
                      () => Text(
                        "${_controller.periodBean.value.year + 2000}/${_controller.periodBean.value.month}/${_controller.periodBean.value.day}",
                        style: _trailingStyle,
                      ),
                    ),
                    onTap: () {
                      _clickStartTime(_controller.periodBean.value.year + 2000,
                          _controller.periodBean.value.month, _controller.periodBean.value.day);
                    },
                  ),

                  //结束时间
                  ListTile(
                    title: Text("持续时间", style: _titleStyle),
                    trailing: Obx(
                      () => Text(
                        "${_controller.periodBean.value.duration}天",
                        style: _trailingStyle,
                      ),
                    ),
                    onTap: () {
                      _clickDurationTime();
                    },
                  ),
                ],
              ),
            ),
          ),

          //占位
          const Expanded(child: SizedBox()),
          //确认按钮
          Container(
            width: double.infinity,
            height: 46,
            margin: const EdgeInsets.symmetric(horizontal: 20),
            child: TextButton(
              onPressed: () {
                _confirm();
              },
              style: ButtonStyle(
                backgroundColor: MaterialStateProperty.all(Colors.blue),
                foregroundColor: MaterialStateProperty.all(Colors.white),
                shape: MaterialStateProperty.all(
                  const RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(Radius.circular(30)),
                  ),
                ),
              ),
              child: const Text('确认'),
            ),
          ),
          const SizedBox(height: 60),
        ],
      ),
    );
  }

  _clickDurationTime() {
    TextEditingController textController = TextEditingController();
    Get.defaultDialog(
      title: '持续时间',
      content: Column(
        children: [
          const Text("0~255分钟"),
          TextField(
            controller: textController,
            onChanged: (v) {},
            decoration: const InputDecoration(
                hintText: "请输入持续天数(天)",
                hintStyle: TextStyle(
                  color: Color(0xFF969696),
                ),
                border: InputBorder.none),
            keyboardType: TextInputType.number,
            inputFormatters: [
              FilteringTextInputFormatter.digitsOnly, //数字，只能是整数
            ],
            maxLines: 1,
          ),
        ],
      ),
      textConfirm: '确定',
      textCancel: '取消',
      onConfirm: () {
        // 用户点击确认按钮时执行的操作
        if (textController.text.isNotEmpty) {
          int mDuration = int.parse(textController.text);
          var temp = _controller.periodBean.value;
          temp.duration = mDuration;
          _controller.updatePeriodBean(temp);
        }
        Get.back();
      },
      onCancel: () {
        // 用户点击取消按钮时执行的操作
      },
    );
  }

  _clickStartTime(int year, int month, int day) {
    Pickers.showDatePicker(
      context,
      mode: DateMode.YMD,
      selectDate: PDuration(year: year, month: month, day: day),
      onConfirm: (p) {
        var temp = _controller.periodBean.value;
        temp.year = (p.year ?? 2000) - 2000;
        temp.month = p.month ?? 0;
        temp.day = p.day ?? 0;
        _controller.updatePeriodBean(temp);
      },
    );
  }

  /// 提交信息到手表
  _confirm() {
    //将数据传送给手表 write
    _controller.updateNeedClosePage(1);
    var mData = _makeDataForWatch();
    BleUtil.writeBleData(_mac, BleUtil.makeWriteData(functionId: _functionId, data: mData));
  }

  ///整合要提交的数据
  List<int> _makeDataForWatch() {
    List<int> result;
    var temp = _controller.periodBean.value;
    int resSwitch = (temp.isSwitch) ? 1 : 0;
    result = ProtocolDataUtil.instance!
        .period(resSwitch, temp.year, temp.month, temp.day, temp.duration);
    return result;
  }
}
